garysimpson.dev
Mobile development with swift and flutter

Expandable Grid Dividers in SwiftUI

August 24, 2023 at 8:00AM

I ran into an odd issue where expanding and collapsing an HStack with two items would lead to padding getting messed up for 1 of the views. Ended up using a Grid. Since there isnt a divider property the Grid needed 3 columns with the middle being fixed width. Google and ChatGPT were not helpful for me. I landed on this approach the hard way. ⚒


DualColumnDividedView

/// Returns a LazyVGrid containing the LeftSectionUIView and RightSectionUIView.
/// - NOTE: For .top alignment functionality we use a 3 column grid with middle grid being a fixed width VDivider.

func getDualColumnDividedGrid() -> some View {
    let columns: [GridItem] = [
      GridItem(.flexible(), spacing: 16, alignment: .top),
      GridItem(.fixed(16), spacing: 8, alignment: .top),
      GridItem(.flexible(), spacing: 16, alignment: .top)
    ]

    return LazyVGrid(columns: columns ) {
         LeftSectionUIView()
         VDividerUIView()
         RightSectionUIView()
     }
}


VDividerUIView

Oddly enough I realized I the stock divider was not ideal since it seems to be oriented to be used in vertical use. I expected it to just work when place in an Grid or HStack. That failed so I made my own.

struct VDividerUIView: View {
  var body: some View {
      Color.auxilary
            .frame(width: 1)
  }
}

Summary

The trick with the code above was keeping the Grid items alignment to .top . That was the main think the internet seemed to miss in all their approaches. It was fighting the language imo.

SwiftUI and LazyGrid for the win on that one. It wouldve been a pain to make that work with UIStackView or NSAnchors. Easily 70+ lines if it wasnt in SwiftUI.


Happy Coding ;-)